package thu.sorit.resolver;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import android.graphics.Bitmap;
import android.util.Log;

public class SinaResolver implements Resolver {

	@Override
	public boolean owns(String url) {
		return url.contains("sina.com.cn");
	}
	
	@Override
	public Video fillVideo(String url) {
		Video v = new Video();
		v.url = url;
		try {
			Element head = Jsoup.connect(url).get().head();
			String script = head.getElementsByTag("script").first().html();
			int s = script.indexOf("pic:") + 6;
			int e = script.indexOf("'", s);
			v.preview = Util.getBitmapFromURL(script.substring(s, e));
			s = script.indexOf("vid :") + 6;
			e = script.indexOf("'", s);
			int vid = Integer.parseInt(script.substring(s, e));
			Document d = Jsoup.connect("http://v.iask.com/v_play.php?vid=" + vid).get();
			v.duration = Integer.parseInt(d.getElementsByTag("length").first().html()) / 1000;
			v.title = d.getElementsByTag("vname").first().html();
			v.cdn = d.getElementsByTag("url").first().html();
		} catch (Exception e) {
		}
		return v;
	}

	@Override
	public List<Video> search(String keyword, Bitmap preview, int duration,
			double threshold) {
		ArrayList<Video> ret = new ArrayList<Video>();
		try {
			Document doc = Jsoup.connect("http://video.sina.com.cn/search/index.php?k=" + keyword).get();
			Elements eles = doc.body().getElementById("contentH").getElementsByClass("videoPic");
			for (Element e : eles) {
				int d = Util.timeToDuration(e.getElementsByClass("timetxt").first().html());
				double t = 1 - Math.abs(d - duration) / (double) duration;
				if (t < 0.95) {
					Log.i("peterfff", "drop one because of duration");
					continue;
				}
				Bitmap b = Util.getBitmapFromURL(e.getElementsByTag("img").first().attr("src"));
				double s = Util.getBitmapSimilarity(preview, b);
				b.recycle();
				if (t / 2 + s / 2 > threshold) {
					Log.i("peterfff", "find one in sina");
					ret.add(fillVideo(e.getElementsByTag("a").first().attr("href")));
				} else {
					Log.i("peterfff", "drop one because s = " + s);
				}
			}
		} catch (IOException e1) {
		}
		return ret;
	}

}
